package com.huazi.user.registration.tool;

import java.sql.*;

/**
 * 数据库的工具类
 */
public class BaseDao {
    /**
     * 1.连接
     * 2.释放资源
     * 3.增删改
     * 4.查询
     */
    public static Connection conn;

    /**
     * 获取数据库连接
     *
     * @return
     */
    public Connection createrConn() {
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=utf8", "root", "123456");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     *
     * @param conn
     */
    public void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 增删改的通用方法
     *
     * @param sql
     * @param arr
     * @return
     */
    public int executeUpdate(String sql, Object... arr) {
        Connection connection = createrConn();
        int count = 0;
        try {
            PreparedStatement pst = connection.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {

                pst.setObject(i + 1, arr[i]);
            }
            count = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 通用的查询方法
     *
     * @param sql
     * @param arr
     * @return
     */
    public ResultSet excuteQuery(String sql, Object... arr) {
        Connection connection = createrConn();
        ResultSet rs = null;
        try {
            PreparedStatement pst = connection.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                pst.setObject(i + 1, arr[i]);
            }
            rs = pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
}
